/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
'use strict';

// import * as nls from 'vscode-nls';
// const localize = nls.loadMessageBundle();

//import { languages, window, commands, ExtensionContext, TextDocument, ColorInformation, ColorPresentation, Color, Range, Position, CompletionItem, CompletionItemKind, TextEdit, SnippetString } from 'vscode';
//import { LanguageClient, LanguageClientOptions, ServerOptions, TransportKind } from 'vscode-languageclient';
import { getCSSLanguageService, getSCSSLanguageService, getLESSLanguageService, LanguageService, Stylesheet } from 'vscode-css-languageservice';
//import { ConfigurationFeature } from 'vscode-languageclient/lib/configuration.proposed';
//import { DocumentColorRequest, DocumentColorParams, ColorPresentationRequest, ColorPresentationParams } from 'vscode-languageserver-protocol/lib/protocol.colorProvider.proposed';
interface LanguageModelCache<T> {
	get(document: any): T;
	onDocumentRemoved(document: any): void;
	dispose(): void;
}

function getLanguageModelCache<T>(maxEntries: number, cleanupIntervalTimeInSec: number, parse: (document: any) => T): LanguageModelCache<T> {
	let languageModels: { [uri: string]: { version: number, languageId: string, cTime: number, languageModel: T } } = {};
	let nModels = 0;

	let cleanupInterval = 0;
	if (cleanupIntervalTimeInSec > 0) {
		cleanupInterval = setInterval(() => {
			let cutoffTime = Date.now() - cleanupIntervalTimeInSec * 1000;
			let uris = Object.keys(languageModels);
			for (let uri of uris) {
				let languageModelInfo = languageModels[uri];
				if (languageModelInfo.cTime < cutoffTime) {
					delete languageModels[uri];
					nModels--;
				}
			}
		}, cleanupIntervalTimeInSec * 1000);
	}

	return {
		get(document: any): T {
			let version = document.version;
			let languageId = document.languageId;
			let languageModelInfo = languageModels[document.uri];
			if (languageModelInfo && languageModelInfo.version === version && languageModelInfo.languageId === languageId) {
				languageModelInfo.cTime = Date.now();
				return languageModelInfo.languageModel;
			}
			let languageModel = parse(document);
			languageModels[document.uri] = { languageModel, version, languageId, cTime: Date.now() };
			if (!languageModelInfo) {
				nModels++;
			}

			if (nModels === maxEntries) {
				let oldestTime = Number.MAX_VALUE;
				let oldestUri = null;
				for (let uri in languageModels) {
					let languageModelInfo = languageModels[uri];
					if (languageModelInfo.cTime < oldestTime) {
						oldestUri = uri;
						oldestTime = languageModelInfo.cTime;
					}
				}
				if (oldestUri) {
					delete languageModels[oldestUri];
					nModels--;
				}
			}
			return languageModel;

		},
		onDocumentRemoved(document: any) {
			let uri = document.uri;
			if (languageModels[uri]) {
				delete languageModels[uri];
				nModels--;
			}
		},
		dispose() {
			if (typeof cleanupInterval !== 'undefined') {
				clearInterval(cleanupInterval);
				cleanupInterval = void 0;
				languageModels = {};
				nModels = 0;
			}
		}
	};
}
var vscode;
function initVsCode() {
	vscode = vscode || (vscode = getVsCode("css"));
}
function asTextEdit(edit) {
	if (!edit) {
		return undefined;
	}
	return new vscode.TextEdit(asRange(edit.range), edit.newText);
}
function asTextEdits(items) {
	if (!items) {
		return undefined;
	}
	return items.map(asTextEdit);
}

function asPosition(value) {
	if (!value) {
		return undefined;
	}
	return new vscode.Position(value.line, value.character);
}
function asRange(value) {
	if (!value) {
		return undefined;
	}
	return new vscode.Range(asPosition(value.start), asPosition(value.end));
}
// this method is called when vs code is activated
export function activate(context: any) {
	initVsCode();
	let languageServices: { [id: string]: LanguageService } = {
		css: getCSSLanguageService(),
		scss: getSCSSLanguageService(),
		less: getLESSLanguageService()
	};

	function getLanguageService(document: any) {
		let service = languageServices[document.languageId];
		if (!service) {
			console.log('Document type is ' + document.languageId + ', using css instead.');
			service = languageServices['css'];
		}
		return service;
	}
	// The server is implemented in node
	//let serverModule = context.asAbsolutePath(path.join('server', 'out', 'cssServerMain.js'));
	// The debug options for the server
	//let debugOptions = { execArgv: ['--nolazy', '--inspect=6044'] };

	// If the extension is launch in debug mode the debug server options are use
	// Otherwise the run options are used
	// let serverOptions = {
	// 	run: { module: serverModule, transport: TransportKind.ipc },
	// 	debug: { module: serverModule, transport: TransportKind.ipc, options: debugOptions }
	// };
	let stylesheets = getLanguageModelCache<Stylesheet>(10, 60, document => getLanguageService(document).parseStylesheet(document));
	vscode.workbench.onDidCloseTextDocument(doc => {
		stylesheets.onDocumentRemoved(doc);
	});
	let documentSelector = ['css', 'scss', 'less'];

	// Options to control the language client
	// let clientOptions: LanguageClientOptions = {
	// 	documentSelector,
	// 	synchronize: {
	// 		configurationSection: ['css', 'scss', 'less']
	// 	},
	// 	initializationOptions: {
	// 	}
	// };

	// Create the language client and start the client.
	// let client = new LanguageClient('css', localize('cssserver.name', 'CSS Language Server'), serverOptions, clientOptions);
	// client.registerFeature(new ConfigurationFeature(client));

	//let disposable = client.start();
	// Push the disposable to the context's subscriptions so that the
	// client can be deactivated on extension deactivation
	//context.subscriptions.push(disposable);

	// client.onReady().then(_ => {
	// register color provider
	context.subscriptions.push(vscode.languages.registerColorProvider(documentSelector, {
		provideDocumentColors(document): Thenable<any[]> {

			// let document = vscode.workspace.textDocuments.get(document);
			// if (document) {
			let stylesheet = stylesheets.get(document);
			var symbols = getLanguageService(document).findDocumentColors(document, stylesheet);
			//}
			return TPromise.as(symbols.map(symbol => {
				let range = asRange(symbol.range);
				let color = new vscode.Color(symbol.color.red, symbol.color.green, symbol.color.blue, symbol.color.alpha);
				return new vscode.ColorInformation(range, color);
			}));
			// let params: DocumentColorParams = {
			// 	textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document)
			// };
			// return client.sendRequest(DocumentColorRequest.type, params).then(symbols => {
			// 	return symbols.map(symbol => {
			// 		let range = client.protocol2CodeConverter.asRange(symbol.range);
			// 		let color = new Color(symbol.color.red, symbol.color.green, symbol.color.blue, symbol.color.alpha);
			// 		return new ColorInformation(range, color);
			// 	});
			// });
		},
		provideColorPresentations(color: any, context): any[] | Thenable<any[]> {

			// let document = documents.get(params.textDocument.uri);
			// if (document) {
			let stylesheet = stylesheets.get(document);
			var presentations = getLanguageService(document).getColorPresentations(document, stylesheet, color, asRange(context.range));
			//}
			return presentations.map(p => {
				let presentation = new vscode.ColorPresentation(p.label);
				presentation.textEdit = p.textEdit && asTextEdit(p.textEdit);
				presentation.additionalTextEdits = p.additionalTextEdits && asTextEdits(p.additionalTextEdits);
				return presentation;
			});
			// let params: ColorPresentationParams = {
			// 	textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(context.document),
			// 	color,
			// 	range: client.code2ProtocolConverter.asRange(context.range)
			// };
			// return client.sendRequest(ColorPresentationRequest.type, params).then(presentations => {
			// 	return presentations.map(p => {
			// 		let presentation = new ColorPresentation(p.label);
			// 		presentation.textEdit = p.textEdit && client.protocol2CodeConverter.asTextEdit(p.textEdit);
			// 		presentation.additionalTextEdits = p.additionalTextEdits && client.protocol2CodeConverter.asTextEdits(p.additionalTextEdits);
			// 		return presentation;
			// 	});
			// });
		}
	}));
	// });

	let indentationRules = {
		increaseIndentPattern: /(^.*\{[^}]*$)/,
		decreaseIndentPattern: /^\s*\}/
	};

	vscode.languages.setLanguageConfiguration('css', {
		wordPattern: /(#?-?\d*\.\d\w*%?)|(::?[\w-]*(?=[^,{;]*[,{]))|(([@#.!])?[\w-?]+%?|[@#!.])/g,
		indentationRules: indentationRules
	});

	vscode.languages.setLanguageConfiguration('less', {
		wordPattern: /(#?-?\d*\.\d\w*%?)|(::?[\w-]+(?=[^,{;]*[,{]))|(([@#.!])?[\w-?]+%?|[@#!.])/g,
		indentationRules: indentationRules
	});

	vscode.languages.setLanguageConfiguration('scss', {
		wordPattern: /(#?-?\d*\.\d\w*%?)|(::?[\w-]*(?=[^,{;]*[,{]))|(([@$#.!])?[\w-?]+%?|[@#!$.])/g,
		indentationRules: indentationRules
	});

	const regionCompletionRegExpr = /^(\s*)(\/(\*\s*(#\w*)?)?)?$/;
	vscode.languages.registerCompletionItemProvider(documentSelector, {
		provideCompletionItems(doc, pos) {
			let lineUntilPos = doc.getText(new vscode.Range(new vscode.Position(pos.line, 0), pos));
			let match = lineUntilPos.match(regionCompletionRegExpr);
			if (match) {
				let range = new vscode.Range(new vscode.Position(pos.line, match[1].length), pos);
				let beginProposal = new vscode.CompletionItem('#region', vscode.CompletionItemKind.Snippet);
				beginProposal.range = range; vscode.TextEdit.replace(range, '/* #region */');
				beginProposal.insertText = new vscode.SnippetString('/* #region $1*/');
				beginProposal.documentation = 'Folding Region Start';
				beginProposal.filterText = match[2];
				beginProposal.sortText = 'za';
				let endProposal = new vscode.CompletionItem('#endregion', vscode.CompletionItemKind.Snippet);
				endProposal.range = range;
				endProposal.insertText = '/* #endregion */';
				endProposal.documentation = 'Folding Region End';
				endProposal.sortText = 'zb';
				endProposal.filterText = match[2];
				return [beginProposal, endProposal];
			}
			return null;
		}
	});

	vscode.commands.registerCommand('_css.applyCodeAction', applyCodeAction);

	function applyCodeAction(uri: string, documentVersion: number, edits: any[]) {
		let textEditor = vscode.window.activeTextEditor;
		if (textEditor && textEditor.document.uri.toString() === uri) {
			if (textEditor.document.version !== documentVersion) {
				vscode.window.showInformationMessage(`CSS fix is outdated and can't be applied to the document.`);
			}
			textEditor.edit(mutator => {
				for (let edit of edits) {
					mutator.replace(asRange(edit.range), edit.newText);
				}
			}).then(success => {
				if (!success) {
					vscode.window.showErrorMessage('Failed to apply CSS fix to the document. Please consider opening an issue with steps to reproduce.');
				}
			});
		}
	}
}

